﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Web.Routing;
using Kratos.Framework.Infrastructures;
using Kratos.Framework.Routing;

namespace Kratos.Framework.Extensions.RouteExtensions
{
    public static class RouteCollectionExtensions
    {
        public static void LoadFromModules(this RouteCollection routes, IModulesLoaded modulesLoaded)
        {
            //翻转模块以排列route的优先级
            IEnumerable<IKratosModule> modules = modulesLoaded.GetModules<IKratosModule>().Reverse();

            foreach (var module in modules)
                module.RegisterRoutes(routes);
        }

        public static Route MapLowerCaseRoute(this RouteCollection routes, string name, string url, object defaults, object constraints = null, string[] namespaces = null)
        {
            if (routes == null)
                throw new ArgumentNullException("routes");

            if (url == null)
                throw new ArgumentNullException("url");

            var lowerCaseRoute = new LowerCaseRoute(url, new MvcRouteHandler())
            {
                Defaults = new RouteValueDictionary(defaults),
                Constraints = new RouteValueDictionary(constraints),
                DataTokens = new RouteValueDictionary(new { Namespaces = namespaces })//指定命明空间
            };

            if (!string.IsNullOrEmpty(name))
                routes.Add(name, lowerCaseRoute);
            else
                routes.Add(lowerCaseRoute);

            return lowerCaseRoute;
        }
    }
}
